package com.xingdata.jjxc.activity;

import java.util.HashMap;

import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ab.http.AbRequestParams;
import com.alibaba.fastjson.JSON;
import com.xingdata.jjxc.App;
import com.xingdata.jjxc.R;
import com.xingdata.jjxc.base.Base1Activity;
import com.xingdata.jjxc.enty.RespEntity;
import com.xingdata.jjxc.enty.UserEntity;
import com.xingdata.jjxc.http.HttpResponseListener;
import com.xingdata.jjxc.utils.ActivityTools;
import com.xingdata.jjxc.utils.Code;
import com.xingdata.jjxc.utils.Constants;
import com.xingdata.jjxc.utils.ImageUtils;
import com.xingdata.jjxc.utils.SP;
import com.xingdata.jjxc.utils.SystemInfo;
import com.xingdata.jjxc.views.AnimationView;
import com.xingdata.jjxc.views.Widget;
/**
 * 
 * @author ysc
 *
 * @date 2016-08-24 登录界面 
 */
public class LoginActivity extends Base1Activity implements OnClickListener {

	private TextView login_title;
	private TextView login_register, find_password;
	private Button login_btn;

	private ImageView titleBack;
	private EditText login_phone, login_pwd;
	private ImageView login_pwd_btn_iv;

	protected AbRequestParams params = null;

	protected UserEntity user;

	private String pNum = "";


	private boolean mbDisplayFlg = false;
	public static final int INTENT_CODE_COMMON_ADDRESS = 0;
	public static final int INTENT_CODE_COMMON_FEED = 1;


	private ImageView imageView_pic;
	private MediaPlayer mp;
	private Intent mIntent;
	private Bundle mBundle;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// setContentView(R.layout.activity_loginavt);
		ActivityTools.addActivities(this);
		initData();
	}

	private void initData() {
		user = SP.getUserInfo(this);
		// 设置登录界面背景透明度 
//		((LinearLayout)findViewById(R.id.title_bg_alpha)).getBackground().setAlpha(150);
		if (user != null) {
			if (user.getMobile().length() != 0 && user.getPw().length() != 0) {
				doPost_login(user.getMobile(), user.getPw());
			} else {
				if (mp == null || !mp.isPlaying()) {
					mp = MediaPlayer.create(this, R.raw.m);
					// 重复播放音乐
					mp.setLooping(true);
					mp.start();
				}
				new AnimationView(this, imageView_pic).init();
			}

		}
	}

	@Override
	protected void initViews() {
		login_pwd_btn_iv = (ImageView) findViewById(R.id.login_pwd_btn_iv);
		login_pwd_btn_iv.setOnClickListener(this);
		login_pwd_btn_iv.setBackgroundResource(R.drawable.pwd_open);
		titleBack = (ImageView) findViewById(R.id.title_back);
		titleBack.setOnClickListener(this);
		login_title = (TextView) findViewById(R.id.title);
		login_title.setText("登录");

		login_phone = (EditText) findViewById(R.id.login_phone_et);
		login_pwd = (EditText) findViewById(R.id.login_pwd_et);

		login_register = (TextView) findViewById(R.id.login_register_tv);
		login_register.setOnClickListener(this);

		find_password = (TextView) findViewById(R.id.find_password_tv);
		find_password.setOnClickListener(this);

		login_btn = (Button) findViewById(R.id.login_btn);
		login_btn.setOnClickListener(this);
		imageView_pic = (ImageView) findViewById(R.id.imageView_pic);
		((ImageView) findViewById(R.id.title_delet)).setVisibility(View.GONE);

		if (getIntent().getExtras() != null) {
			String phone = getIntent().getExtras().getString("mobile");
			if (phone != null) {
				login_phone.setText(phone);
			}
		}
		if (!SystemInfo.isDebug) {
			login_phone.setText("13311528681");
			login_pwd.setText("000000");
		}
		// initAnim();
		// initPicture();
		// setListener();
		// /**
		// * 界面刚开始显示的内容
		// */
		// imageView_pic.setImageDrawable(mPicture_1);
		// imageView_pic.startAnimation(mFadeIn);

	}

	@Override
	public void onClick(View v) {
		if (isNetworkConnected() == false) {
			showToast("网络连接断开，请检查网络");
			return;
		}
		pNum = login_phone.getText().toString().trim();
		switch (v.getId()) {

		case R.id.title_back:
			finish();
			break;
		case R.id.login_register_tv:
			mIntent = new Intent(LoginActivity.this,
					ContrastSecurityCodeActivity.class);
			mBundle = new Bundle();
			mBundle.putInt("code", Constants.registerCode);
			mIntent.putExtras(mBundle);
			ActivityTools.startActivity(this, mIntent);
			if (mp!=null&&mp.isPlaying()) {
				mp.stop();
			}
			break;
		case R.id.login_pwd_btn_iv:
			/**
			 * 密码的显示与隐藏
			 */
			if (!mbDisplayFlg) {
				login_pwd_btn_iv.setBackgroundResource(R.drawable.pwd_close);
				login_pwd
						.setTransformationMethod(HideReturnsTransformationMethod
								.getInstance());
			} else {
				login_pwd_btn_iv.setBackgroundResource(R.drawable.pwd_open);
				login_pwd.setTransformationMethod(PasswordTransformationMethod
						.getInstance());
			}
			mbDisplayFlg = !mbDisplayFlg;
			login_pwd.postInvalidate();
			login_pwd.setSelection(login_pwd.getText().toString().trim()
					.length());
			break;

		case R.id.login_btn:
			String pPsw = login_pwd.getText().toString().trim();

			if (pNum.equals("") || (pNum.length() != 11)) {
				showToast(R.string.error_phone_num);
			} else if (!pNum.substring(0, 2).equals("13")
					&& !pNum.substring(0, 2).equals("15")
					&& !pNum.substring(0, 2).equals("17")
					&& !pNum.substring(0, 2).equals("18")) {
				showToast(R.string.invalid_phone_num);
			} else if (pPsw.equals("")) {
				showToast(R.string.error_input_pwd);
			} else {
				Widget.withDrawKeyboard(this);
				doPost_login(pNum, pPsw);
			}
			// startActivity(new Intent(Loginavt.this,MainActivity.class));
			// finish();
			break;

		case R.id.find_password_tv:
			mIntent = new Intent(LoginActivity.this,
					ContrastSecurityCodeActivity.class);
			mBundle = new Bundle();
			mBundle.putInt("code", Constants.findPWCode);
			mBundle.putString("pNum", pNum);
			mIntent.putExtras(mBundle);
			ActivityTools.startActivity(this, mIntent);
			if (mp.isPlaying()) {
				mp.stop();
			}
			break;
		default:
			break;
		}
	}

	
//	private void doPost_checkVersion(String url) {
//		paramsMap = new HashMap<String, String>();
//		paramsMap.put("access_token", Code.accessToken());
//		String strVersionName = "22" + "130";
//		paramsMap.put("version", strVersionName);
//		mHttpUtil.Post(url, paramsMap, new HttpResponseListener() {
//			@Override
//			public void onSuccess(RespEntity respEntity) {
//				// TODO Auto-generated method stub
//				System.out.println(":");
//			}
//			@Override
//			public void onLoading(int vurrent) {
//				// TODO Auto-generated method stub
//			}
//			
//			@Override
//			public void onFailure(String result) {
//				
//			}
//		});
//		
//		
//	}
	private void doPost_login(final String mobile, final String password) {
		if (isNetworkConnected() == false) {
			showToast("网络连接断开，请检查网络");
			return;
		}
		paramsMap = new HashMap<String, String>();
		paramsMap.put("mobile", mobile);
		paramsMap.put("password", password);
		mHttpUtil.Post(App.ZZD_REQUEST_LOGIN, paramsMap,
				new HttpResponseListener() {

					@Override
					public void onSuccess(RespEntity entity) {
						// SharedPreTools.putString(LoginActivity.this,
						// Common.USERNAME, mobile);
						// SharedPreTools.putString(LoginActivity.this,
						// Common.PASSWORD,Jni.Jni_encryptionStr(password,
						// mobile));
						UserEntity user = JSON.parseObject(entity.getResult(),
								UserEntity.class);
						// 获取Token
						TokenEntity tokenEntity = new TokenEntity();
						tokenEntity.setToken(Code.accessToken(mobile, password,
								user.getUserid()));
						SystemInfo.setTokenEntity(tokenEntity);
						user.setMobile(mobile);
						user.setToken(tokenEntity.getToken());
						user.setPw(password);
						SP.saveUserInfo(LoginActivity.this, user);
						// baocuo
						// carHudlist =
						// JUtils.getcarHudList(entity.getHudlist());
						// SP.saveHudInfo(LoginActivity.this,
						// entity.getHudlist());
						nextController();
						
//						doPost_checkVersion("http://jjxc.hudim.com/index.php/Hud/Api/System/softupdate");
					}

					@Override
					public void onFailure(String result) {
						showToast(result);
					}

					@Override
					public void onLoading(int vurrent) {
						// TODO Auto-generated method stub

					}
				});
	}

	protected boolean isNetworkConnected() {
		ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		cwjManager.getActiveNetworkInfo();
		boolean netSataus = true;
		if (cwjManager.getActiveNetworkInfo() == null) {
			netSataus = false;
		}
		return netSataus;
	}

	private void nextController() {
		startActivity(new Intent(LoginActivity.this, MainActivity.class));
		ActivityTools.finish();
	};


	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();

		if (mp != null && mp.isPlaying()) {
			mp.stop();
		}
//		ImageUtils.releaseImageViewResouce(imageView_pic);
	}

	@Override
	protected int getContentViewId() {
		return R.layout.activity_loginavt;
	}

	@Override
	protected String getTitleText() {
		// TODO Auto-generated method stub
		return "";
	}
	
	
	

}
